package com.lechi.web.framework.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class JwtTokenUtil {
    private static final String SECRET_KEY = "lechi@2025"; // 密钥，用于签名和验证 Token
    private static final long EXPIRATION_TIME = 1800000; // 30 分钟

    private static final long STATIC_EXPIRATION_TIME =  TimeUnit.DAYS.toMillis(10000);

    // 生成动态 JWT Token
    public static String generateDynamicToken(String userAccount) {
        return Jwts.builder()
                .setSubject(userAccount)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .claim("token_type", "dynamic")
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public static String generateStaticToken(String userAccount) {
        return Jwts.builder()
                .setSubject(userAccount)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + STATIC_EXPIRATION_TIME))
                .claim("token_type", "static")
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public static Claims validateStaticToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();

            // 新增token类型校验
            if (!"static".equals(claims.get("token_type"))) {
                return null;
            }
            return claims;
        } catch (Exception e) {
            return null;
        }
    }

    // 验证动态 JWT Token
    public static Claims validateDynamicToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();

            // 新增token类型校验
            if (!"dynamic".equals(claims.get("token_type"))) {
                return null;
            }
            return claims;
        } catch (Exception e) {
            return null;
        }
    }

    // 通过静态 token 获取动态 token
    public static String getDynamicTokenByStaticToken(String staticToken) {
        Claims claims = validateStaticToken(staticToken);
        if (claims != null) {
            return generateDynamicToken(claims.getSubject());
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(generateStaticToken("hztald"));

        System.out.println(validateStaticToken("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJseW5zeiIsImlhdCI6MTc0NzE4NjA5NSwiZXhwIjoyNjExMTg2MDk1LCJ0b2tlbl90eXBlIjoic3RhdGljIn0.ZRfLzzIA0WtslTeXRBraLkbCGjdXkXPG12w9wg3_MOc").getExpiration());
    }
}